﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;

namespace KouDai.Phone.Controls
{
    public class DependencyPropertyListener
    {
        private static int index;
        private readonly DependencyProperty property;
        private FrameworkElement target;
        public event EventHandler<BindingChangedEventArgs> Changed;

        public DependencyPropertyListener()
        {
            this.property = DependencyProperty.RegisterAttached
                (
                "DependencyPropertyListener" + DependencyPropertyListener.index++,
                typeof(object),
                typeof(DependencyPropertyListener),
                new PropertyMetadata(null, HandleValueChanged)
                );
        }

        private void HandleValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            this.OnChanged(new BindingChangedEventArgs(e));
        }

        protected void OnChanged(BindingChangedEventArgs e)
        {
            EventHandler<BindingChangedEventArgs> changed = this.Changed;
            if (changed != null)
            {
                changed(this.target, e);
            }
        }

        public void Attach(FrameworkElement element, Binding binding)
        {
            if (this.target != null)
            {
                throw new Exception("Cannot attach an already attach listener");
            }
            this.target = element;
            this.target.SetBinding(property, binding);
        }

        public void Detach()
        {
            this.target.ClearValue(this.property);
            this.target = null;
        }
    }
}
